﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medecine.Interface.Main;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
using Medecine.Interface.Users;

namespace Medecine.Interface.Utils
{
	/// <summary>
	/// Command requiring a user with rights.
	/// </summary>
	public class RightCommand : RelayCommand, INotifyPropertyChanged
	{
		public RightCommand(Action execute)
			: this(execute, () => true)
		{
		}

		public RightCommand(Action execute, Func<bool> canExecute)
			: base(execute, canExecute)
		{
			ViewModelLocator.MainStatic.PropertyChanged += MainPropertyChanged;
		}

		private void MainPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "ActiveUser")
			{
				RaisePropertyChanged("IsAllowed");
			}
		}

		public bool IsAllowed { get { return ViewModelLocator.MainStatic.CanInvokeCommand(); } }

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void RaisePropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = this.PropertyChanged;
			if (handler != null)
				handler(this, new PropertyChangedEventArgs(propertyName));
		}
	}

	/// <summary>
	/// Command requiring a user with rights.
	/// </summary>
	public class RightCommand<T> : RelayCommand<T>, INotifyPropertyChanged
	{
		public RightCommand(Action<T> execute)
			: this(execute, (t) => true)
		{
		}

		public RightCommand(Action<T> execute, Func<T, bool> canExecute)
			: base(execute, canExecute)
		{
			ViewModelLocator.MainStatic.PropertyChanged += MainPropertyChanged;
		}

		private void MainPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "ActiveUser")
			{
				RaisePropertyChanged("IsAllowed");
			}
		}

		public bool IsAllowed
		{
			get
			{
				UserViewModel user = ViewModelLocator.MainStatic.ActiveUser;
				return (user != null) && (user.Role != "Infirmière");
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void RaisePropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = this.PropertyChanged;
			if (handler != null)
				handler(this, new PropertyChangedEventArgs(propertyName));
		}
	}
}
